package com.hgyc.mom.mes.controller;

import com.hgyc.mom.common.context.FileServiceContext;
import com.hgyc.mom.common.util.file.FileUtils;
import com.hgyc.mom.common.util.http.HttpUtils;
import com.hgyc.mom.common.vo.Result;
import com.hgyc.mom.mes.entity.SopAttachment;
import com.hgyc.mom.mes.service.SopAttachmentService;
import com.hgyc.mom.tool.entity.SopAppVersion;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.UnsupportedEncodingException;

/**
 * sop上传文件Controller
 *
 * @author fwj
 * @since 2025-06-18
 */
@Tag(name = "sop上传文件控制器", description = "sop上传文件控制器")
@RestController
@RequestMapping("/mes/sop/attachment")
public class SopAttachmentController {
    @Autowired
    private SopAttachmentService sopAttachmentService;

    @Autowired
    private FileServiceContext fileServiceContext;

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public Result<?> uploadFile(@RequestParam("file") MultipartFile file) throws Exception
    {
        try
        {
            SopAttachment sysAttachment = sopAttachmentService.uploadFile(file);

            return Result.success("上传成功！",sysAttachment);
        }
        catch (Exception e)
        {
            return Result.error(e.getMessage());
        }
    }

    @DeleteMapping("/delete/{id}")
    public Result<?> deleteFile(@PathVariable("id") Long id) {
        sopAttachmentService.removeAttachment(id);
        return Result.success();
    }

    @Operation(summary = "下载文档", description = "下载安装包")
    @GetMapping("/download/{id}")
    public void download(@PathVariable("id") Long id, HttpServletResponse response) throws UnsupportedEncodingException {
        SopAttachment sopAttachment = sopAttachmentService.getById(id);
        byte[] file = fileServiceContext.downloadFile(sopAttachment.getFileUrl());
        String fileName = java.net.URLEncoder.encode(sopAttachment.getFileName(), "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename="+fileName);
        HttpUtils.writeData(response, file, "application/octet-stream");
    }
}
